<template>
  <div class="designer-container">
    <div class="toolbar">
      <h2>页面设计器</h2>
      <div class="actions">
        <el-input v-model="pageName" placeholder="页面名称" style="width: 200px;"></el-input>
        <el-button type="primary" @click="savePage">保存页面</el-button>
        <el-button @click="exportCode">导出代码</el-button>
        <el-button @click="previewPage">预览页面</el-button>
      </div>
    </div>

    <div class="designer-content">
      <!-- 左侧组件库 -->
      <div class="component-library">
        <h4>组件库</h4>
        <div class="components-list">
          <div 
            v-for="comp in componentList" 
            :key="comp.type"
            class="component-item"
            draggable="true"
            @dragstart="startDrag($event, comp)">
            <i :class="comp.icon"></i>
            <span>{{ comp.label }}</span>
          </div>
        </div>
      </div>

      <!-- 中间设计区 -->
      <div class="canvas-area"
        @dragover.prevent="isDragOver = true"
        @dragleave="isDragOver = false"
        @drop="onCanvasDrop"
        :class="{ 'drag-over': isDragOver }">
        <div class="canvas-content">
          <div v-if="components.length === 0" class="empty-tip">
            从左侧拖拽组件到此区域
          </div>
          <div 
            v-for="(comp, index) in components" 
            :key="comp.id"
            class="canvas-component"
            :class="{ 'selected': selectedIndex === index }"
            @click="selectComponent(index)">
            <div class="component-toolbar">
              <el-button 
                type="text" 
                size="small" 
                @click.stop="removeComponent(index)"
                style="color: #f56c6c;">删除</el-button>
            </div>
            <component-render :comp="comp"></component-render>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <h4>属性设置</h4>
        <div v-if="selectedIndex !== null && components[selectedIndex]" class="property-form">
          <el-form size="small" label-width="70px">
            <el-form-item label="类型">
              <span>{{ components[selectedIndex].type }}</span>
            </el-form-item>
            <el-form-item label="文本内容" v-if="['text', 'button'].includes(components[selectedIndex].type)">
              <el-input v-model="components[selectedIndex].content" placeholder="输入文本内容"></el-input>
            </el-form-item>
            <el-form-item label="图片URL" v-if="components[selectedIndex].type === 'image'">
              <el-input v-model="components[selectedIndex].src" placeholder="输入图片URL"></el-input>
            </el-form-item>
            <el-form-item label="字体大小">
              <el-input-number v-model="components[selectedIndex].fontSize" :min="12" :max="48" size="small"></el-input-number>
            </el-form-item>
            <el-form-item label="宽度">
              <el-input v-model="components[selectedIndex].width" placeholder="如: 100%, 300px"></el-input>
            </el-form-item>
            <el-form-item label="高度">
              <el-input v-model="components[selectedIndex].height" placeholder="如: auto, 100px"></el-input>
            </el-form-item>
            <el-form-item label="背景色">
              <el-color-picker v-model="components[selectedIndex].backgroundColor"></el-color-picker>
            </el-form-item>
            <el-form-item label="文字色">
              <el-color-picker v-model="components[selectedIndex].color"></el-color-picker>
            </el-form-item>
            <el-form-item label="内边距">
              <el-input v-model="components[selectedIndex].padding" placeholder="如: 10px 15px"></el-input>
            </el-form-item>
            <el-form-item label="外边距">
              <el-input v-model="components[selectedIndex].margin" placeholder="如: 10px 0"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div v-else class="empty-tip">
          点击画布中的组件来编辑属性
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog title="页面预览" :visible.sync="previewVisible" width="80%" top="5vh">
      <div class="preview-content">
        <div 
          v-for="comp in components" 
          :key="comp.id"
          :style="getComponentStyle(comp)">
          <component-render :comp="comp"></component-render>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const ComponentRender = {
  props: ['comp'],
  template: `
    <div :style="getStyle()">
      <img v-if="comp.type === 'image'" :src="comp.src" :style="{ maxWidth: '100%', height: 'auto' }" />
      <button v-else-if="comp.type === 'button'" :style="getStyle()" disabled>{{ comp.content }}</button>
      <input v-else-if="comp.type === 'input'" :placeholder="comp.content" disabled />
      <div v-else-if="comp.type === 'text'" :style="getStyle()">{{ comp.content }}</div>
      <div v-else-if="comp.type === 'box'" :style="getStyle()">盒子容器</div>
    </div>
  `,
  methods: {
    getStyle() {
      return {
        fontSize: this.comp.fontSize + 'px',
        width: this.comp.width,
        height: this.comp.height,
        backgroundColor: this.comp.backgroundColor,
        color: this.comp.color,
        padding: this.comp.padding,
        margin: this.comp.margin,
        border: '1px solid #ddd',
        borderRadius: '4px',
        boxSizing: 'border-box'
      }
    }
  }
}

export default {
  name: 'PageDesigner',
  components: {
    ComponentRender
  },
  data() {
    return {
      pageName: '',
      isDragOver: false,
      selectedIndex: null,
      previewVisible: false,
      componentId: 0,
      components: [],
      componentList: [
        { type: 'text', label: '文本', icon: 'el-icon-document-copy' },
        { type: 'button', label: '按钮', icon: 'el-icon-circle-check' },
        { type: 'input', label: '输入框', icon: 'el-icon-edit' },
        { type: 'image', label: '图片', icon: 'el-icon-picture' },
        { type: 'box', label: '容器', icon: 'el-icon-crop' }
      ]
    }
  },
  methods: {
    startDrag(event, comp) {
      event.dataTransfer.effectAllowed = 'copy'
      event.dataTransfer.setData('componentType', comp.type)
    },

    onCanvasDrop(event) {
      event.preventDefault()
      this.isDragOver = false
      
      const componentType = event.dataTransfer.getData('componentType')
      if (componentType) {
        const newComp = {
          id: `comp-${++this.componentId}`,
          type: componentType,
          content: '组件内容',
          src: 'https://via.placeholder.com/200',
          fontSize: 14,
          width: '100%',
          height: 'auto',
          backgroundColor: '#ffffff',
          color: '#333333',
          padding: '10px',
          margin: '5px 0'
        }
        this.components.push(newComp)
        this.selectedIndex = this.components.length - 1
      }
    },

    selectComponent(index) {
      this.selectedIndex = index
    },

    removeComponent(index) {
      this.components.splice(index, 1)
      this.selectedIndex = null
    },

    getComponentStyle(comp) {
      return {
        fontSize: comp.fontSize + 'px',
        width: comp.width,
        height: comp.height,
        backgroundColor: comp.backgroundColor,
        color: comp.color,
        padding: comp.padding,
        margin: comp.margin,
        border: '1px solid #ddd',
        borderRadius: '4px',
        boxSizing: 'border-box'
      }
    },

    savePage() {
      if (!this.pageName.trim()) {
        this.$message.error('请输入页面名称')
        return
      }

      const pageData = {
        name: this.pageName,
        content: JSON.stringify(this.components),
        description: '页面设计器创建的页面'
      }

      console.log('保存的页面数据:', pageData)
      this.$message.success('页面保存成功')
    },

    exportCode() {
      if (this.components.length === 0) {
        this.$message.error('页面为空')
        return
      }

      let html = `<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${this.pageName || '页面'}</title>
    <style>
      body { margin: 0; padding: 20px; font-family: Arial, sans-serif; }
      .container { max-width: 1200px; margin: 0 auto; }
    </style>
</head>
<body>
    <div class="container">
`

      this.components.forEach(comp => {
        const style = `style="font-size: ${comp.fontSize}px; width: ${comp.width}; height: ${comp.height}; background-color: ${comp.backgroundColor}; color: ${comp.color}; padding: ${comp.padding}; margin: ${comp.margin}; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"`
        
        if (comp.type === 'text') {
          html += `        <div ${style}>${comp.content}</div>\n`
        } else if (comp.type === 'button') {
          html += `        <button ${style}>${comp.content}</button>\n`
        } else if (comp.type === 'input') {
          html += `        <input type="text" placeholder="${comp.content}" ${style} />\n`
        } else if (comp.type === 'image') {
          html += `        <img src="${comp.src}" ${style} />\n`
        } else if (comp.type === 'box') {
          html += `        <div ${style}>容器</div>\n`
        }
      })

      html += `    </div>\n</body>\n</html>`

      const element = document.createElement('a')
      element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(html))
      element.setAttribute('download', `${this.pageName || '页面'}.html`)
      element.style.display = 'none'
      document.body.appendChild(element)
      element.click()
      document.body.removeChild(element)
      
      this.$message.success('页面代码导出成功')
    },

    previewPage() {
      if (this.components.length === 0) {
        this.$message.error('页面为空')
        return
      }
      this.previewVisible = true
    }
  }
}
</script>

<style scoped>
.designer-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.toolbar {
  background: white;
  padding: 15px 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 10px;
}

.designer-content {
  flex: 1;
  display: flex;
  gap: 10px;
  padding: 10px;
  overflow: hidden;
}

.component-library {
  width: 150px;
  background: white;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.component-library h4 {
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.components-list {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.component-item {
  padding: 8px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 3px;
  cursor: move;
  font-size: 12px;
  text-align: center;
  user-select: none;
  transition: all 0.2s;
}

.component-item:hover {
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.canvas-area {
  flex: 1;
  background: white;
  border-radius: 4px;
  border: 2px dashed #ddd;
  padding: 10px;
  overflow-y: auto;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.canvas-area.drag-over {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.canvas-content {
  min-height: 100%;
}

.empty-tip {
  color: #909399;
  text-align: center;
  padding: 40px 20px;
  font-size: 14px;
}

.canvas-component {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.canvas-component:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.canvas-component.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.component-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
  gap: 5px;
}

.property-panel {
  width: 220px;
  background: white;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.property-panel h4 {
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.property-form {
  font-size: 12px;
}

.preview-content {
  padding: 20px;
  max-width: 1200px;
}
</style>
